package com.crb.oauth2.api.wechat.cp.controller;

import com.crb.oauth2.api.wechat.cp.common.RestfulResult;
import com.crb.oauth2.api.wechat.cp.config.WxCpConfiguration;
import com.crb.oauth2.api.wechat.cp.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxError;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.WxCpUserService;
import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import me.chanjar.weixin.cp.bean.WxCpUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;


/**
 * OAuth2.0
 *
 * @author huangjian
 */
@Slf4j
@Controller
@RequestMapping("/wx/cp/oauth/{agentId}")
public class WxH5OauthController extends BaseController{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("/oauth2")
    public String oauth2() {
        return "oauth2";
    }

    /**
     * 暴露给前端的接口
     * @param agentId
     * @param code
     * @return
     */
    @ResponseBody
    @RequestMapping("/greetUser/{code}")
    public RestfulResult greetUser(@PathVariable Integer agentId, @PathVariable String code) {
        WxCpService cpService = WxCpConfiguration.getCpService(agentId);
        if (cpService==null) {
            return RestfulResult.error(String.format("未找到对应agentId=[%s]的配置，请核实！", agentId));
        }
        try {
            WxCpOauth2UserInfo userInfo = cpService.getOauth2Service().getUserInfo(code);
            String openId = userInfo.getOpenId();
            String userId = userInfo.getUserId();
            WxCpUserService userService = cpService.getUserService();
            //兼容企业微信和微信两种认证方式
            if(!StringUtils.isNotEmpty(userId)) {
                userId = userService.openid2UserId(openId);
            }
            WxCpUser user = userService.getById(userId);
            return RestfulResult.success(user);
        } catch (WxErrorException e) {
            e.printStackTrace();
            WxError error = e.getError();
            return RestfulResult.error(error.getErrorCode(),error.getErrorMsg());
        }
    }

    @RequestMapping("/toOauth2")
    public String toOauth2(@PathVariable Integer agentId) {
        WxCpService cpService = WxCpConfiguration.getCpService(agentId);
        String url = super.getServerDomain()+"/wx/cp/oauth/" + agentId + "/greet";
        String redirect_uri = "";
        try {
            redirect_uri = java.net.URLEncoder.encode(url, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.error("ecdoe error: " + e.getMessage());
        }
        String redirectUrl = cpService.getOauth2Service().buildAuthorizationUrl(redirect_uri, WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
        logger.info("redirectUrl="+redirectUrl);
        return "redirect:" + redirectUrl;
    }



    @RequestMapping("/greet")
    public String greetUser(@PathVariable Integer agentId, @RequestParam String code, ModelMap map) {
        WxCpService cpService = WxCpConfiguration.getCpService(agentId);
        if (cpService==null) {
            throw new IllegalArgumentException(String.format("未找到对应agentId=[%s]的配置，请核实！", agentId));
        }
        try {
            WxCpOauth2UserInfo userInfo = cpService.getOauth2Service().getUserInfo(code);
            String openId = userInfo.getOpenId();
            String userId = userInfo.getUserId();
            WxCpUserService userService = cpService.getUserService();
            //兼容企业微信和微信两种认证方式
            if(!StringUtils.isNotEmpty(userId)) {
                userId = userService.openid2UserId(openId);
            }
            WxCpUser user = userService.getById(userId);
            map.put("user", user);
            log.info(JsonUtils.toJson(user));
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return "greet_user";
    }

}
